import {defineStore} from 'pinia';
import UserApi from '../api/user_mock.js'
import {GroupItem, ContactsItem, Chatting} from '../models/contacts.ts';
import {User} from "../models/contacts.ts";
import {toRaw} from "vue";


// 定义 state 类型
interface ChatStoreState {
    user?: User;
    chatList: Chatting[];
    groups: GroupItem[];
    contacts: ContactsItem[];
    blacklist: string[]; //黑名单列表
    applyList: any[]; //好友申请列表
}

// 定义一个 name 为‘blogStore’的 store
export const useChatStore = defineStore('blogStore', {
    // 第三方插件的持久化配置
    persist: {
        enabled: true,
        strategies: [{
            storage: localStorage
        }]
    },
    state: (): ChatStoreState => {
        return {
            user: null, //当前user
            // 聊天列表数据
            chatList: [], // 聊天列表数据
            groups: [], // 群组列表数据
            contacts: [], // 联系人列表数据
            blacklist: [], // 黑名单 ID 列表数据
            applyList: [] // 申请好友列表
        };
    },
    getters: {
        getChatList(state): any[] {
            return state.chatList;
        },
        getContactList(state): ContactsItem[] {
            return state.contacts || [];
        },
        getGroupList(state): GroupItem[] {
            return state.groups;
        },
        getBlacklist(state): string[] {
            // 返回 id
            return state.blacklist;
        },
        getFriendsIds(state): string[] {
            // 返回 id
            return state.contacts?.map(e => e.userId) || [];
        },
        getApplyList(state): any[] {
            return state.applyList;
        }
    },
    actions: {
        /**
         * 刷新联系人列表
         */
        async refreshContacts() {
            console.debug("refreshContacts ...")
            let resp = await UserApi.findContactList();

            this.contacts = resp.data.friends;
            this.blacklist = resp.data.blackIds;
        }

        /**
         * 刷新群组列表
         */
        , async refreshChatGroups() {
            console.debug("refreshChatGroups ...")
            let resp = await UserApi.findChatGroupList();
            this.groups = resp.data;
        }

        // /**
        //  * 刷新聊天列表
        //  */
        // , async refreshChatterRelationList() {
        //     // console.debug("refreshChatterRelationList ...")
        //     const resp = await UserApi.findChatterRelationList();
        //     this.chatList = resp.data.map(e =>
        //         this.buildChatContext(e)
        //     )
        // }

        /**
         * 根据groupNo，查询chatGroup
         * @param userId
         * @returns {Promise<*>}
         */
        , getGroupById(groupId: string) {
            if (!groupId) {
                new Error("groupId不能为空");
            }
            return this.groups.find(group => {
                return String(group.groupNo) === String(groupId)
            })
        }

        /**
         * 根据contact的userId，获取聊天对象
         * @param contactId
         * @returns {*}
         */
        , getChattingByRelId(relId: string) {
            if (!relId) {
                new Error("chatId 不能为空");
            }
            // console.debug(">> getChattingByRelId relId = "+relId)

            return this.chatList.find(chat => {
                if ("groupNo" in chat.chatter) {
                    return (String(chat.chatter.relId) === String(relId))
                }
                else if ("userId" in chat.chatter) {
                    return (String(chat.chatter.userId) === String(relId))
                }
            })
        }

        /**
         * 添加聊天对象到列表首位
         * @param chatContext
         */
        , addToChatList(chatting: Chatting) {
            let index = this.chatList.indexOf(chatting)
            if (index < 0) {
                this.chatList.push(chatting); //添加到数组中
            }
        }

        // /**
        //  * 根据聊天关系对象，构建聊天对象
        //  * @param chatUser
        //  * @returns {ChatContext}
        //  */
        // , buildChatContext(chatterRelation) {
        //     const context = new ChatContext(chatterRelation.relId)
        //     context.chatUser = chatterRelation.chatUser
        //     context.name = chatterRelation.chatUser.nickname;
        //     context.avatarUrl = chatterRelation.chatUser.avatarUrl;
        //     context.isFriend = chatterRelation.isFriend;
        //     context.isOnline = chatterRelation.isOnline;
        //     context.uid = chatterRelation.userId;
        //     return context;
        // }
        //
        , obtainChatting(chatter: ContactsItem | GroupItem) {
            console.debug("obtainChatting ... ");
            let chatting;

            if ("groupNo" in chatter) {
                // console.debug(">>> GroupItem ...")
                chatting = this.getChattingByRelId((chatter as GroupItem).relId);
            }
            else if ("userId" in chatter) {
                // console.debug(">>> ContactsItem ...")
                chatting = this.getChattingByRelId((chatter as ContactsItem).userId);
            }

            if (!chatting) {
                console.debug("create Chatting ... ");
                if (!this.user) {
                    new Error("user数据不能为空")
                }
                chatting = new Chatting(toRaw(this.user!), chatter);
            } else {
                console.debug("without create Chatting ... ");
            }
            this.addToChatList(chatting)
            return chatting;
        }
    }
});